package com.apes.fn.business.fixedLoss.service;

import com.apes.fn.business.fixedLoss.modle.BusinessStrategy;
import com.apes.fn.business.fixedLoss.repository.BusinessStrategyRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName BusinessStrategyService
 * @Author wsj
 * @Date 2021/5/7 15:06
 * @description 商务业务策略业务层
 */
@Service("businessStrategyService")
public class BusinessStrategyService extends DomainService {
    @Autowired
    private BusinessStrategyRepository strategyRepository;


    public BusinessStrategy save(SimpleRequest request) {
        BusinessStrategy businessStrategy = request.getO(BusinessStrategy.class);
        businessStrategy.setState("create");
        businessStrategy.checkValidPeriod();
        return strategyRepository.saveAndFlush(businessStrategy);
    }


    public BusinessStrategy update(SimpleRequest request) {
        checkData(request);
        BusinessStrategy businessStrategy = request.getO(BusinessStrategy.class);
        businessStrategy.checkValidPeriod();
        return strategyRepository.saveAndFlush(businessStrategy);
    }


    public BusinessStrategy delete(SimpleRequest request) throws Exception  {
        checkData(request);
        BusinessStrategy businessStrategy = request.getO(BusinessStrategy.class);
        businessStrategy.setState("delete");
        businessStrategy.setDeleteDate(new Date());
        businessStrategy.setDeleteUid(this.getPerson(request));
        return  strategyRepository.saveAndFlush(businessStrategy);
    }

    private void checkData(SimpleRequest request) {
        String id = request.get("id");
        int versions = (int) request.get("version");
        BusinessStrategy businessStrategy = strategyRepository.findOne(id);
        if (businessStrategy == null){
            throw new RuntimeException( id + "在系统中不存在!!!");
        }
        if (businessStrategy.getVersion() != versions){
            throw new RuntimeException("记录已更新或已删除，请重新提交！");
        }
    }
    public BusinessStrategy approve(SimpleRequest request) {
        checkData(request);
        BusinessStrategy businessStrategy = request.getO(BusinessStrategy.class);
        businessStrategy.setState("approve");
        businessStrategy.setApproveDate(new Date());
        businessStrategy.setApproveUid(this.getPerson(request));
        return  strategyRepository.saveAndFlush(businessStrategy);
    }

    public void repeal(SimpleRequest request) {
        checkData(request);
        BusinessStrategy businessStrategy = request.getO(BusinessStrategy.class);
        businessStrategy.setState("repeal");
        strategyRepository.saveAndFlush(businessStrategy);
    }
}
